package com.example.myimageshare.View;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.myimageshare.Utils.MediaPathUtil;
import com.example.myimageshare.domain.User;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myimageshare.R;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;

import java.io.File;
import java.util.List;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

public class UserInfoActivity extends AppCompatActivity {

    public static final String TAG = UserInfoActivity.class.getSimpleName(); //日志
    private static final int REQUEST_CODE_CHOOSE = 23;//定义请求码常量

    private ImageView iv_user_head;
    private TextView tv_username;
    private TextInputEditText tiet_nicknam;
    private TextInputEditText tiet_signature;
    private Toolbar toolbar;
    private Button bt_confirm_update;

    private User user;
    private  List<Uri> mSelected;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        initView();
        initData();
        initAction();

    }

    private void initView(){
        toolbar = findViewById(R.id.toolbar);
        iv_user_head = findViewById(R.id.iv_user_info);
        tv_username = findViewById(R.id.tv_info_username);
        tiet_nicknam = findViewById(R.id.tiet_info_nickname);
        tiet_signature = findViewById(R.id.tiet_info_signature);
        bt_confirm_update = findViewById(R.id.bt_confirm_update);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


    }

    private void initData(){
        user = BmobUser.getCurrentUser(User.class);
        Log.d(TAG,"用户名为："+ user.getUsername());

        tv_username.setText(user.getUsername());
        Log.d(TAG,"用户昵称为："+ user.getNickname());

        tiet_nicknam.setText(user.getNickname());
        Log.d(TAG,"用户个性签名为："+ user.getSignature());
        tiet_signature.setText(user.getSignature());

        Log.d(TAG,"用户头像URL为："+ user.getHeadimg());

        Glide.with(this)
                .load(user.getHeadimg())
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(iv_user_head);

//        BmobUser.logOut();

    }

    private void initAction(){
        iv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initMatiss();

            }
        });

        bt_confirm_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateUserInfo();
            }
        });
    }

    /*修改个人信息*/
    private void updateUserInfo(){

        final User user = BmobUser.getCurrentUser(User.class);
        String nickname = tiet_nicknam.getText().toString();
        String signature = tiet_signature.getText().toString();
        user.setNickname(nickname);
        user.setSignature(signature);
        user.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.d(TAG,"更新用户信息成功");
                    Toast.makeText(UserInfoActivity.this,
                            "更新用户信息成功",
                            Toast.LENGTH_SHORT).show();

                } else {
                    Log.d(TAG,"更新用户信息失败");
                    tiet_nicknam.setText(BmobUser.
                            getCurrentUser(User.class)
                            .getNickname());
                    tiet_signature.setText(BmobUser
                            .getCurrentUser(User.class)
                            .getSignature());
                }
            }
        });
    }

    private void initMatiss(){
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(1)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(false) // Default is `true`
                .forResult(REQUEST_CODE_CHOOSE);



    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);

            String realPath = MediaPathUtil.getRealPathFromURI(this,
                    Matisse.obtainResult(data).get(0));
            Log.d(TAG,realPath );

            upload(realPath);


        }
    }

    /*上传头像*/
    private void upload(String picPath){
        final BmobFile bmobFile = new BmobFile(new File(picPath));
        bmobFile.uploadblock(new UploadFileListener() {

            @Override
            public void done(BmobException e) {
                if(e==null){
                    //bmobFile.getFileUrl()--返回的上传文件的完整地址
                    Toast.makeText(UserInfoActivity.this,"上传完成！",
                            Toast.LENGTH_SHORT).show();
                    //同时，更新用户名的头像URL
                    final User user = BmobUser.getCurrentUser(User.class);
                    user.setHeadimg(bmobFile.getFileUrl());
                    user.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                Glide.with(UserInfoActivity.this)
                                        .load(bmobFile.getUrl())
                                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                        .into(iv_user_head);
                                Log.d(TAG,"更新头像成功");

                                Toast.makeText(UserInfoActivity.this,"更新头像成功",
                                        Toast.LENGTH_SHORT).show();

                            } else {
                                Log.d(TAG,"更新头像失败");
                            }
                        }
                    });

                }else{
                    Toast.makeText(UserInfoActivity.this,"上传失败！",
                            Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onProgress(Integer value) {
                // 返回的上传进度（百分比）
            }
        });
    }

}
